package com.zl.bootsecurityjwt.common.exception;

import com.alibaba.fastjson.JSONObject;
import com.zl.bootsecurityjwt.common.constant.HttpStatus;
import com.zl.bootsecurityjwt.common.utils.ResponseMapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常拦截处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map = new HashMap<>();
        if (e instanceof PreAuthorizeException) {
            log.info("权限不足，无法访问系统资源....");
            map.put("status", HttpStatus.FORBIDDEN);
            map.put("info", "权限不足，无法访问系统资源");
        }else if (e instanceof InternalAuthenticationServiceException) {
            log.info("该用户不存在，请从新输入....");
            map.put("status", HttpStatus.NOT_USER);
            map.put("info", "该用户不存在，请从新输入....!");
        }else if(e instanceof BadCredentialsException) {
            log.info("用户登录时身份认证失败，请从新输入....");
            map.put("status", HttpStatus.NOT_FOUND);
            map.put("info", "用户登录时身份认证失败....!");
        }
        return map;
    }
}
